package com.lyn.tool.mvp.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;

import androidx.annotation.Nullable;

import com.lyn.plugin.utils.LogUtil;
import com.lyn.plugin.entity.Plugin;
import com.lyn.plugin.PluginHelper;
import com.lyn.tool.databinding.ActivityMainBinding;
import com.lyn.tool.databinding.AdapterPluginBinding;
import com.lyn.tool.mvp.contract.MainContract;
import com.lyn.tool.mvp.other.Result;
import com.lyn.tool.mvp.presenter.MainPresenter;
import com.lyn.tool.mvp.view.adapter.BaseAdapter;
import com.lyn.tool.utils.FileUtil;

import java.util.List;


public class MainActivity extends BaseActivity<ActivityMainBinding> implements MainContract.View
        , AdapterView.OnItemClickListener {


    private BaseAdapter<Plugin, AdapterPluginBinding> pluginAdapter;
    private MainPresenter mainPresenter;

    @Override
    public ActivityMainBinding getViewBinding() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }

    @Override
    public void create(@Nullable Bundle savedInstanceState) {
        mainPresenter = new MainPresenter(this);
        pluginAdapter = new BaseAdapter<Plugin, AdapterPluginBinding>() {
            @Override
            protected AdapterPluginBinding getViewBinding() {
                return AdapterPluginBinding.inflate(getLayoutInflater());
            }

            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            protected void onViewHolder(AdapterPluginBinding binding, Plugin plugin) {
                if (plugin.getLogoId() != 0) {
                    binding.icons.setBackground(plugin.getResources().getDrawable(plugin.getLogoId()));
                }
                binding.name.setText(plugin.getName());
            }

        };

        viewBinding.pluginGridView.setAdapter(pluginAdapter);
        viewBinding.pluginGridView.setOnItemClickListener(this);
        //加载插件
        mainPresenter.loadPlugin(FileUtil.getInstance().getPluginRootPath());

    }


    @Override
    public void onLoading() {
        showLoading();
    }

    @Override
    public void onHideLoading() {
        hideLoading();
    }

    @Override
    public void onResult(Result result) {
        toast(result.getMsg());
        if (result.getCode() == Result.SUCCESS) {
            List<Plugin> listData = result.getListData(Plugin.class);
            pluginAdapter.setData(listData);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Plugin plugin = pluginAdapter.getItem(position);
        PluginHelper.startActivity(this, plugin);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}